//
//  HLManager.m
//  nmrsc
//
//  Created by xumckay on 16/1/9.
//  Copyright © 2016年 bric. All rights reserved.
//

#import "HLManager.h"
#import "VersionsCheckView.h"
#import <arpa/inet.h> //检查是否有网络那个方法要导入的东西
#import "MBProgressHUD.h"

#define kPhoneRegex @"^[1][3,4,5,7,8,9][\\d]{9}$"
#define kEmailRegex @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"

@interface HLManager ()
@property (strong,nonatomic)MBProgressHUD *HUD;


@end

@implementation HLManager

//获取单例
+(HLManager * )sharedManager
{
    static HLManager*_hlManager=nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        _hlManager=[[self alloc]init];
    });
    return _hlManager;
}

//获取afnetworiking支持https的配置
-(AFSecurityPolicy*)getHttpsSetting
{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    securityPolicy.validatesCertificateChain = NO;
    return securityPolicy;
}

-(instancetype)init
{
    self=[super init];
    if (self) {
        [self initSomeData];
    }
    return self;
}

/// 默认的设置
- (void)initSomeData
{
    AFNetworkReachabilityManager *netWorkReachability = [AFNetworkReachabilityManager sharedManager];
    [netWorkReachability startMonitoring];

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable: {
                NSLog(@"无网络");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: {
                NSLog(@"WiFi网络");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                NSLog(@"2G,3G,4G,5G网络");
                break;
            }
            default:
                break;
        }
    }];

    ////处理网络状态变化的刷新///主要应对从无网络到有网络的变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshSomeData:) name:AFNetworkingReachabilityDidChangeNotification object:nil];

    ///////////设置进入应用，推送的消息提示置为0；注意此处，IOS7以下可以直接设置 ，以上要做如下处理
    if ([[UIDevice currentDevice].systemName floatValue] > 7.0) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
}

/// 网络发生变化时的通知
- (void)refreshSomeData:(NSNotification *)noti
{
    if (KversonIsAppstore == NO) {
        [[HLManager sharedManager] performSelector:@selector(checkCompulsory_version) withObject:nil afterDelay:kAfterDelayTime];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkChange object:nil];
}

// 检测版本更新
- (void)checkCompulsory_version
{
    [[VersionsCheckView sharedVersionCheck] checkVersions];
}

/// 判断是否有网络
- (BOOL)checkIsHasNetworkFunction
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

/// 检查手机号是否正确
- (BOOL)checkPhoneNum:(NSString *)phone
{
    NSString *regex2 = kPhoneRegex;
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    BOOL isMatch2 = [pred2 evaluateWithObject:phone];
    return isMatch2;
}

/// 检查邮箱是否正确
- (BOOL)checkEmailAddress:(NSString *)email
{
    NSString *regex2 = kEmailRegex;
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    BOOL isMatch2 = [pred2 evaluateWithObject:email];
    return isMatch2;
}


//显示弹出提示框，自动隐藏的。。
- (void)showHudText:(NSString *)text detailsText:(NSString *)detailsText afterDelay:(float)delay
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_HUD) {
            [_HUD removeFromSuperview];
            _HUD = nil;
        }

        _HUD = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        _HUD.margin = 15.f;
        _HUD.dimBackground = NO;
        _HUD.mode = MBProgressHUDModeText;
        [[UIApplication sharedApplication].keyWindow addSubview:_HUD];
        NSLog(@"显示的指示器标题是 %@",text);
        _HUD.labelText = text;
        _HUD.labelFont = [UIFont systemFontOfSize:13];
        if (detailsText.length) {
            _HUD.detailsLabelText = detailsText;
        } else {
            _HUD.detailsLabelText = nil;
        }
        [_HUD show:YES];
        [_HUD hide:YES afterDelay:delay];
    });
}

/// 获取内容的cgsize
- (CGSize)getSizeWithContent:(NSString *)content sizeOfAnyView:(UIView*)anyView font:(CGFloat)font
{
    CGRect contentBounds = [content boundingRectWithSize:CGSizeMake(anyView.width,anyView.height)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font]
                                                                                     forKey:NSFontAttributeName]
                                                 context:nil];
    return contentBounds.size;
}

/// 处理电话号码
- (NSMutableString *)makeDownWithTextField:(UITextField *)textField
{
    NSMutableString *str = [[NSMutableString alloc] initWithString:[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""]];
    return str;
}

- (BOOL)isOver5S
{
    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    if (w  <= 320) {
        return NO;
    }else{
        return YES;
    }
    
}

//判断是否登录成功
-(BOOL)isLoginSuccess
{
    NSUserDefaults *user=[[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    
    if ([[user objectForKey:@"memberId"] intValue]==0) {
        
        return NO;
    }
    else
    {
        return YES;
    }
}


@end
